<template>
    <div class='menu-role'>
        <el-row :gutter="20">
            <el-col :span="12">
                <div>
                    <div class="title">
                        <!-- <el-button type="primary" @click="addMenu" >添加菜单</el-button> -->
                        <ChfToolbar :toolbarConfig="toolbarConfig" />
                    </div>
                    <ChfTree v-bind="treeConfig" :style="{ padding: '14px 16px'}" ref="tree" class="tree"></ChfTree>
                </div>
            </el-col>
            <el-col :span="12">
                <div>
                    <div class="title" v-if="menuData">
                        <template v-if="menuData.isButton">
                            编辑按钮：{{menuData.title}}
                        </template>
                        <template v-else>
                            编辑菜单：{{menuData.meta.title}}
                        </template>
                    </div>
                    <ChfForm v-bind="formConfig" v-model="formConfig.formData" :style="{ padding: '14px 16px' }" v-if="menuData">
                        <template #iconList="{form}">
                            <el-form-item label="图标" prop="icon" :rules="[{ required: true, message: '请选择icon',trigger: 'change'}]">
                                <el-select v-model="form.icon" placeholder="请选择" style="width:100%" popper-class="select" clearable>
                                    <el-option :label="item" :value="item" class="option" v-for="item in iconList" :key="item">
                                        <i :class="item"></i>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </ChfForm>
                    <div style="padding:14px 16px" v-else>
                        <el-alert title="从菜单列表选择一项后，进行编辑" :closable="false" type="info" effect="dark">
                        </el-alert>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import ChfTree from "@/components/chf-tree/index.vue"
import addMenuFormConfig from "./addMenuFormConfig.js"
import ChfToolbar from "@/components/chf-toolbar/index.vue"
import iconJson from './icon.json'
export default {
    components: {
        ChfTree, ChfToolbar
    },
    data () {
        return {
            addOrEdit: true,//true添加  false编辑
            formItems: [
                {
                    formItem: { label: "标题", required: true, },
                    itemRender: { el: "el-input", placeholder: "标题", value: "title" },
                },
                {
                    formItem: { label: "按钮" },
                    itemRender: {
                        el: "el-switch", value: "isButton", defVal: false, events: {
                            change: (val) => {
                                if (val) {
                                    if (this.addOrEdit) {
                                        this.addMenuFormConfig.items = this.filterFormItems([2, 3, 4, 5])
                                    } else {
                                        this.formConfig.items = this.filterFormItems([2, 3, 4])
                                    }
                                } else {
                                    if (this.addOrEdit) {
                                        this.addMenuFormConfig.items = this.filterFormItems([4, 5])
                                    } else {
                                        this.formConfig.items = this.filterFormItems([4])
                                    }
                                }
                            }
                        }
                    },
                },
                {
                    formItem: { label: "路径", required: true, },
                    itemRender: { el: "el-input", placeholder: "路径", value: "path" },
                },
                {
                    formItem: { label: "菜单Name", required: true, },
                    itemRender: { el: "el-input", placeholder: "菜单Name", value: "name" },
                },
                {
                    slotName: 'iconList',
                    value: {
                        icon: ''
                    }
                },
                {
                    type: 'button',
                    formItem: {
                        children: [
                            {
                                content: "确定", submit: true, type: 'primary', click: async (form) => {
                                    if (form.isButton) {
                                        this.menuData.title = form.title;
                                        this.menuData.isButton = form.isButton;
                                    } else {
                                        this.menuData.name = form.name;
                                        this.menuData.path = form.path
                                        this.menuData.meta.title = form.title;
                                        form.icon && (this.menuData.meta.icon = form.icon)
                                    }
                                    const { result } = await this.$api.addMenu(this.treeConfig.options.data)
                                    result && this.$message.success('编辑成功！')
                                }
                            },
                            { content: "重置", reset: true }
                        ],
                    },
                },
            ],
            iconList: iconJson,
            menuData: null,
            checkedKeys: [],
            treeConfig: {
                options: {
                    data: [],
                    // props: {
                    //     label: 'meta.title',
                    //     children: 'zones',
                    //     isLeaf: 'leaf',
                    // },
                    ['expand-on-click-node']: false,
                    ['default-expand-all']: true,
                    ['filter-node-method'] (value, data) {
                        console.log(value)
                        if (!value) return true;
                        return data.name.indexOf(value) !== -1;
                    },
                    ['show-checkbox']: true,
                    ['node-key']: "id",
                    ['render-content']: (h, { node, data, store }) => {
                        return (
                            <span class="custom-tree-node">
                                {
                                    node.level === 1 ? <i class={data.meta.icon}></i> : ''
                                }
                                {
                                    data.isButton === true ? <span>{data.title}</span> : <span>{data.meta.title}</span>
                                }

                            </span>
                        )
                    },
                },
                events: {
                    ['check']: (data, checkedData) => {
                        this.checkedKeys = checkedData.checkedKeys;
                        if (this.checkedKeys[0]) {
                            this.toolbarConfig[1].disabled = false;
                        } else {
                            this.toolbarConfig[1].disabled = true;
                        }
                        console.log(this.checkedKeys)
                    },
                    ['node-click']: async (data, node) => {
                        console.log(data)
                        this.addOrEdit = false;
                        //是否显示图标
                        if (node.level === 1) {
                            this.formConfig.items = this.filterFormItems([1])
                        } else {
                            if (data.isButton) {
                                this.formConfig.items = this.filterFormItems([2, 3, 4])
                            } else {
                                this.formConfig.items = this.filterFormItems([4])
                            }
                        }

                        //是否选中菜单
                        if (this.menuData && this.menuData === data) {
                            this.menuData = null;
                            this.$refs.tree.getRefs().setCurrentKey()
                            this.toolbarConfig[0].children[1].disabled = true;
                        } else {
                            this.menuData = data;
                            //选中的菜单为按钮
                            if (data.isButton) {
                                this.formConfig.formData.title = data.title
                                this.formConfig.formData.isButton = data.isButton
                                this.toolbarConfig[0].children[1].disabled = true;
                            } else {
                                this.formConfig.formData.title = data.meta.title
                                this.formConfig.formData.icon = data.meta.icon
                                this.formConfig.formData.path = data.path
                                this.formConfig.formData.name = data.name
                                this.toolbarConfig[0].children[1].disabled = false;
                            }

                        }
                    }
                }
            },
            formConfig: {
                options: {
                    labelWidth: "100px",
                    gutter: 40
                },
                items: [],
                formData: {},
            },
            toolbarConfig: [
                {
                    content: "添加菜单",
                    type: "primary",
                    icon: "el-icon-plus",
                    children: [
                        { content: '添加主菜单', click: () => this.addMenu() },
                        { content: '添加子菜单', disabled: true, click: () => this.addMenu(this.menuData) }
                    ]
                },
                {
                    content: "删除",
                    icon: "el-icon-delete",
                    disabled: true,
                    click: () => {
                        this.$confirm('删除菜单, 是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(async () => {
                            let checkedKeys = this.checkedKeys;
                            this.treeConfig.options.data = filterTreeData(this.treeConfig.options.data)
                            function filterTreeData (list) {
                                return list.filter(item => {
                                    item.children?.[0] && (item.children = filterTreeData(item.children))
                                    return !checkedKeys.includes(item.id)
                                })
                            }
                            const { result } = await this.$api.addMenu(this.treeConfig.options.data)
                            result && this.$message.success('删除成功！')
                            this.checkedKeys = [];
                            this.toolbarConfig[1].disabled = true;
                        })
                    }
                },
                {
                    content: "全部选中",
                    icon: "el-icon-delete",
                    click: async () => {
                        let arr = [];
                        filterTreeData(this.treeConfig.options.data);
                        function filterTreeData (list) {
                            list.forEach(item => {
                                item.children?.[0] && filterTreeData(item.children)
                                arr.push(item.id)
                            })
                        }
                        this.checkedKeys = arr;
                        console.log(this.checkedKeys);
                        this.$refs.tree.getRefs().setCheckedNodes(this.treeConfig.options.data);
                        this.toolbarConfig[1].disabled = false;
                    }
                },
                {
                    content: "全部取消",
                    icon: "el-icon-delete",
                    click: async () => {
                        this.$refs.tree.getRefs().setCheckedKeys([]);
                        this.toolbarConfig[1].disabled = true;
                    }
                },
            ],
            addMenuFormConfig: addMenuFormConfig.call(this)
        }
    },
    created () {
        this.getMenuList();
    },
    methods: {
        async getMenuList () {
            const { result } = await this.$api.getMenuList();
            this.treeConfig.options.data = result;
            console.log(result);
        },
        addMenu (menuData) {
            this.addOrEdit = true;
            //是否显示图标
            if (menuData) {
                this.addMenuFormConfig.items = this.filterFormItems([4, 5])
            } else {
                this.addMenuFormConfig.items = this.filterFormItems([1, 5])
            }
            this.$dialog({
                options: {
                    title: '添加菜单',
                    center: true,
                    width: '430px',
                    close: () => {
                        this.addOrEdit = false;
                    }
                },
                btns: [
                    {
                        submit: true, type: "primary", content: "确定", click: (options) => {
                            console.log(this.$refs.form);
                            this.$refs.form.submitForm().then(async params => {
                                console.log(menuData);

                                if (menuData) {
                                    menuData.children ?? (this.$set(menuData, 'children', []))
                                    menuData.children.push({
                                        meta: { title: params.title },
                                        name: params.name,
                                        path: params.path,
                                        id: new Date().getTime()
                                    })
                                } else {
                                    console.log(this.treeConfig.options.data);
                                    this.treeConfig.options.data.push({
                                        meta: { title: params.title, icon: params.icon },
                                        name: params.name,
                                        path: params.path,
                                        id: new Date().getTime()
                                    })
                                }
                                const { result } = await this.$api.addMenu(this.treeConfig.options.data)
                                // let interfaceType = 'addTable'
                                // if (row) {
                                //     interfaceType = 'editTable'
                                // }
                                // const res = await this.$api[interfaceType](params);
                                // res && this.$message({
                                //     message: row ? '编辑成功！' : '添加成功！',
                                //     type: 'success'
                                // });
                                // this.$refs.grid.getData();
                                options.dialogVisible = false
                            })
                        }
                    },
                    {
                        content: "取消", click: (options) => {
                            options.dialogVisible = false
                        }
                    }
                ],
                render: () => {
                    return (
                        <ChfForm  {...{ attrs: this.addMenuFormConfig }} ref="form" scopedSlots={{
                            iconList: ({ form }) => {
                                return (
                                    <el-form-item label="图标" prop="icon" rules={[{ required: true, message: '请选择icon', trigger: 'change' }]}>
                                        <el-select value={form.icon} onInput={(value) => { form.icon = value }} placeholder="请选择" style="width:100%" popper-class="select" clearable>
                                            {
                                                this.iconList.map(item => {
                                                    return <el-option label={item} value={item} class="option" key={item}>
                                                        <i class={item}></i>
                                                    </el-option>
                                                })
                                            }
                                        </el-select>
                                    </el-form-item>
                                );
                            }
                        }} />
                    )
                },
            })
        },
        filterFormItems (list = []) {
            return this.formItems.filter((item, i) => {
                return !list.includes(i)
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.menu-role {
    height: 100%;
    .el-row {
        height: 100%;
        .el-col {
            height: 100%;
            & > div {
                display: flex;
                flex-direction: column;
                // padding: 10px;
                height: 100%;
                border-radius: 10px;
                border: 1px solid rgb(235, 232, 232);
                overflow: hidden;
                .title {
                    padding: 0 16px;
                    border-bottom: 1px solid #e8eaec;
                    height: 60px;
                    display: flex;
                    align-items: center;
                }
                .tree {
                    flex: 1;
                    height: 0;
                    overflow-y: scroll;
                }
            }
        }
    }
}
</style>
<style lang="scss" >
.select {
    width: 433px;
    .el-scrollbar__view {
        display: flex;
        flex-wrap: wrap;
        .option {
            // padding: 0 30px;
            display: flex;
            align-items: center;
        }
        i {
            font-size: 25px;
        }
    }
}
</style>